package dao;

import java.util.List;

import model.Supplier;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

public class SupplierDAO {
	private final SessionFactory sf = util.NewHibernateUtil.getSessionFactory();

	@SuppressWarnings("unchecked")
	public List<Supplier> showAllSupplier() {
		try {
			sf.getCurrentSession().beginTransaction();
			return sf.getCurrentSession().createCriteria(Supplier.class).list();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Supplier> showAllSupplierByAll(String key) {
		@SuppressWarnings("rawtypes")
		List supplier = sf
				.getCurrentSession()
				.createCriteria(Supplier.class)
				.add(Restrictions.or(Restrictions.like("id", "%" + key + "%"),
						Restrictions.or(Restrictions
								.like("id", "%" + key + "%"), Restrictions.or(
								Restrictions.like("name", "%" + key + "%"),
								Restrictions.or(Restrictions.like("name", "%"
										+ key + "%"), Restrictions.or(
										Restrictions.like("phone", "%" + key
												+ "%"),
										Restrictions.like("address", "%" + key
												+ "%"))))))).list();

		return supplier;
	}

	public Supplier searchSupplier(String id) {
		try {
			sf.getCurrentSession().beginTransaction();
			return (Supplier) sf.getCurrentSession().get(Supplier.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public boolean deleteSupplier(Supplier e) {
		try {
			sf.getCurrentSession().beginTransaction();
			sf.getCurrentSession().delete(e);
			sf.getCurrentSession().getTransaction().commit();
			return true;
		} catch (Exception e2) {
			e2.printStackTrace();
			return false;
		}
	}

	public boolean updateSupplier(Supplier e) {
		try {
			sf.getCurrentSession().beginTransaction();
			sf.getCurrentSession().saveOrUpdate(e);
			sf.getCurrentSession().getTransaction().commit();
			return true;

		} catch (Exception e2) {
			e2.printStackTrace();
			return false;
		}
	}

	public boolean insertSupplier(Supplier e) {
		try {
			sf.getCurrentSession().beginTransaction();
			sf.getCurrentSession().save(e);
			sf.getCurrentSession().getTransaction().commit();
			return true;
		} catch (Exception em) {
			em.printStackTrace();
			sf.getCurrentSession().getTransaction().rollback();
			return false;
		}
	}

	public List<String> loadSName() {
		try {
			sf.getCurrentSession().beginTransaction();
			String hql = "select name from supplier";
			Query q = sf.getCurrentSession().createQuery(hql);
			@SuppressWarnings({ "unchecked", "unused" })
			List<String> l = q.list();
		} catch (Exception e) {
		}
		return null;
	}

}
